package cn.lyh.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.lyh.config.FileConfig;
import cn.lyh.mapper.FileMapper;
import cn.lyh.service.FileService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.text.MessageFormat;
import java.util.Date;
import java.util.UUID;
@Service
public class FileServiceImpl extends ServiceImpl<FileMapper, cn.lyh.entity.File> implements FileService  {
    private static final Logger log = LoggerFactory.getLogger(FileServiceImpl.class);
    @Resource
    private FileConfig fileConfig;

    /**
     * 文件上传
     * @param file
     * @return
     * @throws Exception
     */
    @Override
    public String upload(MultipartFile file) throws Exception {
        if (file.isEmpty()) {
            throw new Exception("FILE_NOT_EMPTY_ERROR上传文件不可为空");
        }
        //文件大小、文件类型，原始文件名、创建时间、文件保存目录地址
        // 生成文件Id
        String fileId = UUID.randomUUID().toString();
        // 获得文件名
        String fileOriginalName = file.getOriginalFilename();
        log.info("获取上传的文件名=[{}]", fileOriginalName);
        // 获取文件类型
        String fileSuffix = fileOriginalName.substring(fileOriginalName.lastIndexOf(".") + 1);
        // 生成文件名称
        String newFileName = MessageFormat.format("{0}.{1}",
                fileId,
                fileSuffix);
        log.info("生成新的文件名称=[{}]", newFileName);
        // 0配置根路径 + 1路径分割符 + 2日期年月日
        String fullFolderPath = MessageFormat.format("{0}{1}{2}",
                fileConfig.getUploadPath(),
                File.separator,
                DateUtil.format(new Date(),"yyyyMMdd"));
        log.info("上传文件的路径=[{}]", fullFolderPath);

        File fileUIS = new File(fullFolderPath);
        if(!fileUIS.exists()){// 如果不存在文件夹创建文件夹,每天第一次上传文件会创建yyyyMMdd的文件夹
            fileUIS.mkdirs();
        }
        String fileFullName = MessageFormat.format("{0}{1}{2}",
                fullFolderPath, File.separator, newFileName);
        File fullPathFile = new File(fileFullName);
        try {
            file.transferTo(fullPathFile); //保存文件
        } catch (IOException | IllegalStateException ex) {
            log.error("文件=[{}] 上传失败，异常信息=[{}]", fileOriginalName, ex);
            throw new Exception("FILE_UPLOAD_ERROR文件上传失败!");
        }
        cn.lyh.entity.File fileInfo = new cn.lyh.entity.File();
        fileInfo.setId(fileId)
                .setOriginalName(fileOriginalName)
                .setFileSize(file.getSize())
                .setAddress(fileFullName);
        this.save(fileInfo);
        log.info("文件上传数据记录成功=[{}]");
        return fileId;
    }
}
